package peer.share;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;

import peer.Config;
import peer.tools.Mdb;


public class PiecTempGroupMange {
	Thread t;
	HashMap<Mdb, PieceTempGroup> cancheTempGroupTable;
	
	public PiecTempGroupMange(){
		cancheTempGroupTable=new HashMap<Mdb, PieceTempGroup>();
		try {
			ini();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	void ini() throws IOException{
		File tempFile=new File(Config.tempPath);
		tempFile.delete();
		tempFile.createNewFile();
	}
	
	public boolean containsPieceTempGroup(Mdb mdb){
		return cancheTempGroupTable.containsKey(mdb);
	}
	
	public void creatPieceTempGroup(Mdb mdb){
		PieceTempGroup ctg=new PieceTempGroup(mdb);
		cancheTempGroupTable.put(mdb, ctg);
	}
	
	public PieceTempGroup getPieceTempGroup(Mdb mdb){
		return cancheTempGroupTable.get(mdb);
	}
	
	public void removePieceTempGroup(Mdb mdb){
		cancheTempGroupTable.remove(mdb);
	}
	
	
	public boolean containsPiece(Mdb mdb,int pieceNum){
		if(containsPieceTempGroup(mdb)){
			PieceTempGroup ctg=getPieceTempGroup(mdb);
			return ctg.containsPiece(pieceNum);
		}else{
			return false;
		}
	}
	
	public void addPiece(Mdb mdb,int pieceNum,byte[]data) throws IOException{
		if(!containsPieceTempGroup(mdb)){
			creatPieceTempGroup(mdb);
		}
		PieceTempGroup ctg=getPieceTempGroup(mdb);
		ctg.addPiece(pieceNum, data);
	}
	
	public byte[] getPiece(Mdb mdb,int pieceNum) throws IOException{
		PieceTempGroup ctg=getPieceTempGroup(mdb);
		return ctg.getPiece(pieceNum);
	}
}
